import { createSlice, PayloadAction } from '@reduxjs/toolkit';

// 检查是否有有效的访问令牌
const hasAccessToken = (): boolean => {
  try {
    const token = localStorage.getItem('accessToken');
    return !!token;
  } catch {
    return false;
  }
};

interface AuthState {
  isAuthenticated: boolean;
  loading: boolean;
  error: string | null;
}

const initialState: AuthState = {
  isAuthenticated: !!localStorage.getItem('accessToken'),
  loading: false,
  error: null,
};

const authSlice = createSlice({
  name: '@@app/auth',
  initialState,
  reducers: {
    loginStart: (state) => {
      state.loading = true;
      state.error = null;
    },
    loginSuccess: (state) => {
      state.loading = false;
      state.isAuthenticated = true;
      state.error = null;
    },
    loginFailure: (state, action: PayloadAction<string>) => {
      state.loading = false;
      state.isAuthenticated = false;
      state.error = action.payload;
    },
    logout: (state) => {
      state.isAuthenticated = false;
      state.loading = false;
      state.error = null;
    },
    
    // 检查认证状态
    checkAuthStatus: (state) => {
      state.isAuthenticated = hasAccessToken();
    },
  },
});

export const { loginStart, loginSuccess, loginFailure, logout, checkAuthStatus } = authSlice.actions;

export default authSlice.reducer;